package main

import (
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"sync"
)

type Data struct {
	Imgurl string
	Width  string
	Height string
}

type Comic struct {
	Code int
	Msg  string
	Data []Data
}

var wg = sync.WaitGroup{}

func downloadFile(name, url string) {
	// 创建 img 文件夹
	// 发送 HTTP GET 请求并读取响应
	defer wg.Done()
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()

	// 创建新的 JPG 文件并写入数据
	fileName := name
	filePath := filepath.Join("comic", fileName)
	newFile, err := os.Create(filePath)
	if err != nil {
		fmt.Println(err)
	}
	defer newFile.Close()

	_, err = io.Copy(newFile, resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("File saved to %s", filePath)
}

func main() {
	imgDir := "comic"
	fmt.Println("一次20张")
	if err := os.MkdirAll(imgDir, 0755); err != nil {
		fmt.Println("文件夹已存在")
	}
	wg.Add(20)
	for i := 1; i <= 20; i++ {
		resp, err := http.Get("https://api.a20safe.com/api.php?api=9&key=84dabc42d303ad5257f409af895898b3&lx=dongman")
		if err != nil {
			fmt.Println("请求失败：", err)
			return
		}
		defer resp.Body.Close()

		// 解析 JSON 响应
		var com Comic
		err = json.NewDecoder(resp.Body).Decode(&com)
		if err != nil {
			fmt.Println("解析响应失败：", err)
			return
		}
		new_i := i
		go downloadFile(fmt.Sprintf("pixiv%d%d.jpg", rand.Intn(100), new_i), com.Data[0].Imgurl)
	}
	wg.Wait()
}
